/*
 * Copyright 2020-2030 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.gitee.minimalismstyle.fresh.oss.store.impl

import com.gitee.minimalismstyle.fresh.common.core.extra.write
import com.gitee.minimalismstyle.fresh.oss.api.model.OssFile
import com.gitee.minimalismstyle.fresh.oss.config.OssProperties
import com.gitee.minimalismstyle.fresh.oss.store.Store
import org.apache.commons.lang3.time.DateFormatUtils
import org.springframework.stereotype.Service
import java.io.*
import java.util.*

/**
 * 文件上传到本地， 不支持分布式
 * @author maoxiaodong
 */
@Service
class LocalStore(val ossProperties: OssProperties) : Store {

    private val rootPath : String //文件存储路径
        get() = ossProperties.local.rootPath
                .replaceFirst("classes:", this.javaClass.getResource("/").path)

    override fun write(ossFile: OssFile, inputStream: InputStream): String {
        val uuid = UUID.randomUUID().toString()
        val dateString = DateFormatUtils.format(Date(), "yyyy/MM/dd")// 将文件按照年月日分开

        val path = "/${dateString}/${uuid}.${ossFile.extName}"
        val storagePath = File(rootPath + path)
        if (!storagePath.parentFile.exists()) {// 不存在就新建
            storagePath.parentFile.mkdirs()
        }

        FileOutputStream(storagePath).use {
            inputStream.write(it, ossFile.size!!.toInt())
        }
        return path
    }

    override fun read(ossFile: OssFile,  os: OutputStream) {
        val storagePath = File(rootPath + ossFile.path)
        if (!storagePath.parentFile.exists()) {
            storagePath.parentFile.mkdirs()
        }

        FileInputStream(storagePath).use {
            it.write(os, ossFile.size!!.toInt())
        }
    }

    override fun read(ossFile: OssFile): InputStream {
        val storagePath = File(rootPath + ossFile.path)
        if (!storagePath.parentFile.exists()) {
            storagePath.parentFile.mkdirs()
        }

        return FileInputStream(storagePath)
    }

    override fun delete(path: String) {
        val storagePath = File(rootPath + path)
        if (storagePath.exists()) {
            storagePath.delete()
        }
    }
}